import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/common/index.dart';

import '../../../common/utils/colors.dart';
import '../../../common/models/ceramic_stage_model.dart';
import 'index.dart';

class FiringPage extends GetView<FiringController> {
  const FiringPage({super.key});

  // 主视图
  Widget _buildView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      }

      if (controller.hasError.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48.r, color: Colors.red),
              SizedBox(height: 16.h),
              Text(
                controller.errorMessage.value,
                style: TextStyle(fontSize: 16.sp),
              ),
              SizedBox(height: 24.h),
              ElevatedButton(
                onPressed: () => controller.initData(),
                child: Text('Retry', style: TextStyle(fontSize: 14.sp)),
              ),
            ],
          ),
        );
      }

      return Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(Images.startBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            SizedBox(height: 50.h),
            // 返回和标题
            Padding(
              padding: EdgeInsets.only(left: 20.w),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () => Get.back(),
                    child: Icon(
                      IconFontIcons.iconBack,
                      size: 24.sp,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(width: 110.w),
                  Text(
                    'Timed firing',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ],
              ),
            ),
            // 使用Expanded让SingleChildScrollView填充剩余空间
            Expanded(
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: Column(
                  children: [
                    // Header text
                    Padding(
                      padding: EdgeInsets.only(
                        left: 20.w,
                        right: 20.w,
                        top: 28.h,
                        bottom: 24.h,
                      ),
                      child: Text(
                        'Step-by-step timing records the time required for ceramics to go from the preparation stage to the entire completion stage.',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontFamily: 'Inter',
                        ),
                      ),
                    ),

                    // Timer grid
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: GridView.count(
                        padding: EdgeInsets.zero,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        crossAxisCount: 2,
                        mainAxisSpacing: 16.h,
                        crossAxisSpacing: 16.w,
                        childAspectRatio: 0.85,
                        children: [
                          _buildTimerCard(0, 'Raw material preparation'),
                          _buildTimerCard(1, 'Wheel throwing'),
                          _buildTimerCard(2, 'Dry and leave to crack'),
                          _buildTimerCard(3, 'Repair and decoration'),
                          _buildTimerCard(4, 'Glaze firing'),
                          _buildTimerCard(5, 'Finished product processing'),
                        ],
                      ),
                    ),

                    // Upload and share button
                    Padding(
                      padding: EdgeInsets.all(20.w),
                      child: _buildUploadButton(),
                    ),

                    // 底部说明文本
                    Padding(
                      padding: EdgeInsets.only(
                        bottom: 20.h,
                        left: 20.w,
                        right: 20.w,
                      ),
                      child: Text(
                        'After completing each step on time, you can publish your work to the homepage',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontFamily: 'Inter',
                        ),
                      ),
                    ),
                    // 添加底部安全区域高度
                    SizedBox(
                      height: MediaQuery.of(Get.context!).padding.bottom,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  // 计时卡片
  Widget _buildTimerCard(int index, String title) {
    final stage =
        controller.stages.length > index ? controller.stages[index] : null;
    final isActive = controller.currentStageIndex.value == index;
    final isCompleted = stage?.status == CeramicStageStatus.completed;
    final isRunning = stage?.status == CeramicStageStatus.running;

    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF305CA9),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white, width: 2),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Title - 确保标题占据两行高度
          Padding(
            padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 30.h),
            child: SizedBox(
              height: 44.h, // 固定高度确保两行空间
              child: Center(
                child: Text(
                  title,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                    fontSize: 16.sp,
                    height: 1.2,
                  ),
                ),
              ),
            ),
          ),

          SizedBox(height: 14.h),

          // Timer
          GetBuilder<FiringController>(
            id: 'timer',
            builder: (_) {
              String timeDisplay;
              if (isRunning) {
                timeDisplay = controller.formatTime(
                  controller.currentSeconds.value,
                );
              } else if (isCompleted && stage!.durationSeconds > 0) {
                timeDisplay = controller.formatTime(stage.durationSeconds);
              } else {
                timeDisplay = '00:00:00';
              }

              return Text(
                timeDisplay,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  height: 1.1,
                ),
              );
            },
          ),

          Spacer(),

          // 开始按钮边框
          Container(
            width: double.infinity,
            padding: EdgeInsets.only(top: 1.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.r),
                topRight: Radius.circular(10.r),
                bottomLeft: Radius.circular(13.r),
                bottomRight: Radius.circular(13.r),
              ),
            ),
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                color: const Color(0xFF0A3D8E),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(12.r),
                  topRight: Radius.circular(12.r),
                  bottomLeft: Radius.circular(13.r),
                  bottomRight: Radius.circular(13.r),
                ),
              ),
              child: Center(child: _buildStartButton(index)),
            ),
          ),
        ],
      ),
    );
  }

  // 开始按钮
  Widget _buildStartButton(int index) {
    final stage =
        controller.stages.length > index ? controller.stages[index] : null;
    final bool canStart =
        stage != null &&
        (stage.status == CeramicStageStatus.pending ||
            stage.status == CeramicStageStatus.running);
    final bool isRunning = stage?.status == CeramicStageStatus.running;
    final bool isCompleted = stage?.status == CeramicStageStatus.completed;

    return Padding(
      padding: EdgeInsets.only(
        left: 34.w,
        right: 34.w,
        top: 15.h,
        bottom: 17.h,
      ),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFF60A5FA),
          borderRadius: BorderRadius.circular(37.r),
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            borderRadius: BorderRadius.circular(37.r),
            onTap:
                canStart
                    ? () {
                      controller.handleStageAction(index);
                    }
                    : null,
            child: Center(
              child: Padding(
                padding: EdgeInsets.only(
                  left: 20.w,
                  right: 20.w,
                  top: 10.h,
                  bottom: 10.h,
                ),
                child: Text(
                  isCompleted ? 'Done' : (isRunning ? 'Finish' : 'start'),
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 17.sp,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 上传分享按钮
  Widget _buildUploadButton() {
    return GestureDetector(
      onTap: () {
        // 调用控制器中的上传分享功能
        controller.uploadAndShare();
      },
      child: Container(
        width: double.infinity,
        height: 58.h,
        decoration: ShapeDecoration(
          color: const Color(0xFF5490EE),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(29.r),
          ),
        ),
        child: Center(
          child: Text(
            'Upload and share',
            style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
              fontSize: 16.sp,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<FiringController>(
      init: FiringController(),
      id: "firing",
      builder: (_) {
        return Scaffold(
          body: SafeArea(bottom: false, top: false, child: _buildView()),
          backgroundColor: const Color(0xFF1E3A8A),
        );
      },
    );
  }
}
